<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>师生管理</el-breadcrumb-item>
      <el-breadcrumb-item>学生管理</el-breadcrumb-item>
    </el-breadcrumb>

    <hr />

    <!-- 卡片视图区 -->
    <el-card>
      <!-- 搜索区域 -->
      <el-row :gutter="20">
        <el-col :span="7">
          <el-input
            v-model="queryInfo.queryNo"
            placeholder="请输入学号"
            clearable
          >
            <template slot="prepend">学号</template>
          </el-input>
        </el-col>

        <el-col :span="7">
          <el-input v-model="queryInfo.queryName" placeholder="请输入学生姓名">
            <template slot="prepend">姓名</template>
          </el-input>
        </el-col>

        <el-col :span="3">
          <el-button type="primary" @click="getStuList">查询</el-button>
        </el-col>
      </el-row>

      <!-- 功能区域 -->
      <el-row :gutter="10">
        <el-col :span="6">
          <el-button type="primary" @click="addDialogVisible = true"
            >添加学生</el-button
          >
        </el-col>
      </el-row>

      <!-- 用户列表区域 -->
      <el-table :data="stuList" border stripe style="width: 100%">
        <el-table-column
          prop="stuId"
          label="学号"
          width="100px"
        ></el-table-column>
        <el-table-column prop="stuName" label="姓名" sortable></el-table-column>
        <el-table-column prop="stuTel" label="手机号"></el-table-column>
        <el-table-column prop="stuAds" label="家庭住址"></el-table-column>
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <!-- 修改 -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              plain
              @click="showEditDialog(scope.row.stuId)"
              >编辑</el-button
            >

            <!-- 删除按钮 -->
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              plain
              @click="delDialog(scope.row.stuId)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <el-pagination
        @current-change="handleCurrentChange"
        :current-page.sync="queryInfo.page"
        :page-size="queryInfo.size"
        layout="total, prev, pager, next"
        :total="totalPage"
        background
      >
      </el-pagination>
    </el-card>

    <!-- 添加学生信息 -->
    <el-dialog
      title="添加学生"
      :visible.sync="addDialogVisible"
      width="width"
      @close="addDialogClosed"
    >
      <el-form
        ref="addRef"
        :model="addForm"
        :rules="addRules"
        label-width="100px"
      >
        <el-form-item label="所属分院" prop="stuBraId">
          <el-select
            v-model="addForm.stuBraId"
            placeholder="请选择分院"
            @change="getClsById(addForm.stuBraId)"
          >
            <el-option
              v-for="item in deptList"
              :key="item.deptId"
              :label="item.deptName"
              :value="item.deptId"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="所在班级" prop="stuRmId">
          <el-select v-model="addForm.stuRmId" placeholder="请选择班级">
            <el-option
              v-for="item in clsList"
              :key="item.deptId"
              :label="item.deptName"
              :value="item.deptId"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="姓名" prop="stuName">
          <el-input v-model="addForm.stuName"></el-input>
        </el-form-item>

        <el-form-item label="性别" prop="stuSex">
          <el-radio-group v-model="addForm.stuSex">
            <el-radio :label="1">男</el-radio>
            <el-radio :label="0">女</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="身份证" prop="stuPerId">
          <el-input v-model="addForm.stuPerId"></el-input>
        </el-form-item>

        <el-form-item label="联系电话" prop="stuTel">
          <el-input v-model="addForm.stuTel"></el-input>
        </el-form-item>

        <el-form-item label="电子邮件" prop="stuEmail">
          <el-input v-model="addForm.stuEmail"></el-input>
        </el-form-item>

        <el-row :gutter="10">
          <el-col :span="10">
            <el-form-item label="民族" prop="stuNative">
              <el-input v-model="addForm.stuNative"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="10">
            <el-form-item label="籍贯" prop="stuNation">
              <el-input v-model="addForm.stuNation"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="家庭住址" prop="stuAds">
          <el-input v-model="addForm.stuAds"></el-input>
        </el-form-item>

        <el-form-item label="入学年份" prop="time">
          <el-date-picker
            v-model="addForm.time"
            type="year"
            placeholder="选择年"
          >
          </el-date-picker>
        </el-form-item>

        <el-form-item label="学制" prop="stuStudyYear">
          <el-select v-model="addForm.stuStudyYear" placeholder="请选择学制">
            <el-option label="1" value="1"></el-option>
            <el-option label="2" value="2"></el-option>
            <el-option label="3" value="3"></el-option>
            <el-option label="4" value="4"></el-option>
            <el-option label="5" value="5"></el-option>
            <el-option label="6" value="6"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addStu">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 编辑学生信息 -->
    <el-dialog
      title="编辑学生信息"
      :visible.sync="editDialogVisible"
      width="width"
      @close="editDialogClosed"
    >
      <el-form
        ref="editRef"
        :model="editForm"
        :rules="editRules"
        label-width="100px"
      >
        <el-form-item label="所属分院" prop="stuBraId">
          <el-select
            v-model="editForm.stuBraId"
            @change="getClsById(editForm.stuBraId)"
          >
            <el-option
              v-for="item in deptList"
              :key="item.deptId"
              :label="item.deptName"
              :value="item.deptId"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="所在班级" prop="stuRmId">
          <el-select v-model="editForm.stuRmId">
            <el-option
              v-for="item in clsList"
              :key="item.deptId"
              :label="item.deptName"
              :value="item.deptId"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-row :gutter="10">
          <el-col :span="10">
            <el-form-item label="姓名" prop="stuName">
              <el-input v-model="editForm.stuName" disabled></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="10">
            <el-form-item label="学号" prop="stuId">
              <el-input v-model="editForm.stuId" disabled></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="身份证" prop="stuPerId">
          <el-input v-model="editForm.stuPerId" disabled></el-input>
        </el-form-item>

        <el-form-item label="性别" prop="stuSex">
          <el-radio-group v-model="editForm.stuSex">
            <el-radio label="1" disabled>男</el-radio>
            <el-radio label="0" disabled>女</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-row :gutter="10">
          <el-col :span="10">
            <el-form-item label="民族" prop="stuNative">
              <el-input v-model="editForm.stuNative" disabled></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="10">
            <el-form-item label="籍贯" prop="stuNation">
              <el-input v-model="editForm.stuNation" disabled></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="10">
          <el-col :span="10">
            <el-form-item label="入学年份" prop="stuYear">
              <el-input v-model="editForm.stuYear" disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="学制" prop="stuStudyYear">
              <el-input v-model="editForm.stuStudyYear" disabled></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="联系电话" prop="stuTel">
          <el-input v-model="editForm.stuTel"></el-input>
        </el-form-item>

        <el-form-item label="电子邮件" prop="stuEmail">
          <el-input v-model="editForm.stuEmail"></el-input>
        </el-form-item>

        <el-form-item label="家庭住址" prop="stuAds">
          <el-input v-model="editForm.stuAds"></el-input>
        </el-form-item>

        <el-form-item label="当前状态" prop="status">
          <el-select v-model="editForm.status">
            <el-option label="毕业" value="0"></el-option>
            <el-option label="在读" value="1"></el-option>
            <el-option label="休学" value="2"></el-option>
            <el-option label="退学" value="3"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item
          label="公共必修"
          prop="pubCurs"
          v-if="editForm.pubCurs[0] !== null"
        >
          <el-tag
            type="info"
            v-for="item in editForm.pubCurs"
            :key="item.curId"
            >{{ item.curName }}</el-tag
          >
        </el-form-item>

        <el-form-item
          label="个人选修"
          prop="priCurs"
          v-if="editForm.priCurs[0] !== null"
        >
          <el-tag
            v-for="item in editForm.priCurs"
            :key="item.curId"
            closable
            @close="handleClose(item)"
          >
            {{ item.curName }}
          </el-tag>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editSub">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 删除警告框 -->
    <el-dialog title="警告" :visible.sync="delDialogVisible" width="30%">
      <span>您确定要删除此学生吗？</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="delDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="delStuById">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    // 验证邮箱
    var checkEmail = (rule, value, cb) => {
      const regEmail = /^[A-Za-z\d]+([-_.][A-Za-z\d]+)*@([A-Za-z\d]+[-.])+[A-Za-z\d]{2,4}$/
      if (regEmail.test(value)) {
        return cb()
      }
      cb(new Error('邮箱格式有误'))
    }

    // 验证手机号
    var checkMobile = (rule, value, cb) => {
      const regMobile = /^[1][3,4,5,7,8][0-9]{9}$/
      if (regMobile.test(value)) {
        return cb()
      }
      cb(new Error('手机号输入错误'))
    }

    // 验证身份证号
    var checkPerId = (rule, value, cb) => {
      // const reg = /^[1-9]\d{5}(18|19|20|(3\d))\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/
      const reg = /^[0-9]{18}$/
      if (reg.test(value)) {
        return cb()
      }
      cb(new Error('身份证号输入有误'))
    }
    return {
      timer: '',
      timeVule: 3,
      stuList: [],
      queryInfo: {
        page: 1,
        size: 10,
        queryNo: '',
        queryName: ''
      },
      totalPage: 0,
      deptList: [],
      clsList: [],
      // 添加
      addDialogVisible: false,
      addForm: {
        stuBraId: '',
        stuRmId: '',
        stuName: '',
        stuYear: '',
        stuTel: '',
        stuEmail: '',
        stuAds: '',
        stuSex: '',
        stuNation: '',
        stuNative: '',
        stuPerId: '',
        stuStudyYear: '',
        status: 1,
        createBy: '',
        time: ''
      },
      addRules: {
        stuBraId: [{ required: true, message: '请选择分院' }],
        stuRmId: [{ required: true, message: '请选择班级' }],
        stuName: [{ required: true, message: '请填写姓名', trigger: 'blur' }],
        time: [{ required: true, message: '请选择入学年份', trigger: 'blur' }],
        stuTel: [
          { required: true, message: '请填写手机号', trigger: 'blur' },
          {
            validator: checkMobile,
            trigger: 'blur'
          }
        ],
        stuEmail: [
          { required: true, message: '请填写邮箱', trigger: 'blur' },
          {
            validator: checkEmail,
            trigger: 'blur'
          }
        ],
        stuAds: [
          { required: true, message: '请填写家庭住址', trigger: 'blur' }
        ],
        stuSex: [{ required: true, message: '请选择性别', trigger: 'blur' }],
        stuNation: [{ required: true, message: '请填写籍贯', trigger: 'blur' }],
        stuNative: [{ required: true, message: '请填写民族', trigger: 'blur' }],
        stuPerId: [
          { required: true, message: '请填写身份证', trigger: 'blur' },
          {
            validator: checkPerId,
            trigger: 'blur'
          }
        ],
        stuStudyYear: [{ required: true, message: '请选择学制' }]
      },
      // 编辑
      editDialogVisible: false,
      editForm: {
        stuBraId: '',
        stuRmId: '',
        stuId: '',
        stuName: '',
        stuYear: '',
        stuTel: '',
        stuEmail: '',
        stuAds: '',
        stuSex: '',
        stuNation: '',
        stuNative: '',
        stuPerId: '',
        stuStudyYear: '',
        status: '',
        updateBy: '',
        pubCurs: [],
        priCurs: []
      },
      editRules: {
        stuBraId: [{ required: true, message: '请选择分院' }],
        stuRmId: [{ required: true, message: '请选择班级' }],
        time: [{ required: true, message: '请选择入学年份', trigger: 'blur' }],
        stuTel: [
          { required: true, message: '请填写手机号', trigger: 'blur' },
          {
            validator: checkMobile,
            trigger: 'blur'
          }
        ],
        stuEmail: [
          { required: true, message: '请填写邮箱', trigger: 'blur' },
          {
            validator: checkEmail,
            trigger: 'blur'
          }
        ],
        stuAds: [{ required: true, message: '请填写家庭住址', trigger: 'blur' }]
      },
      delStuId: 0,
      delDialogVisible: false
    }
  },
  created() {
    this.getStuList()
  },
  methods: {
    async getStuList() {
      const { data: res } = await this.$http.get('stu/list', {
        params: this.queryInfo
      })
      if (res.code !== 20000) {
        return this.$message.error('获取列表信息失败')
      }
      this.stuList = res.data.list
      this.totalPage = res.data.total
    },
    handleCurrentChange(newPage) {
      this.queryInfo.page = newPage
      this.getStuList()
    },
    async getDeptList() {
      const { data: res } = await this.$http.get('dept/list', {
        params: this.queryInfo
      })
      if (res.code !== 20000) {
        return this.$message.error('获取列表信息失败')
      }
      this.deptList = res.data.list
      this.total = res.data.total
    },
    async getAllDept() {
      const { data: res } = await this.$http.get('dept/allDept')
      if (res.code !== 20000) {
        return this.$message.error('分院列表获取失败!')
      }
      this.deptList = res.data
    },
    async getClsById(id) {
      this.addForm.stuRmId = ''
      const { data: res } = await this.$http.get('dept/allCls/' + id)
      if (res.code !== 20000) {
        return this.$message.error('班级列表获取失败!')
      }
      this.clsList = res.data
    },
    addDialogClosed() {
      this.$refs.addRef.resetFields()
    },
    addStu() {
      var time = new Date(this.addForm.time)
      this.addForm.stuYear = time.getFullYear()
      this.$refs.addRef.validate(async valid => {
        if (!valid) return
        this.addForm.createBy = window.sessionStorage.getItem('rootname')
        const { data: res } = await this.$http.post('stu/add', this.addForm)
        if (res.code === 20005) {
          return this.$message.error('添加失败，学生已存在!')
        } else if (res.code !== 20000) {
          return this.$message.error('添加失败，未知错误!')
        }
        this.addDialogVisible = false
        this.getStuList()
        return this.$message.success('添加成功!')
      })
    },
    // 编辑
    showEditDialog(id) {
      // 定时器
      if (this.timeVule >= 1) {
        this.getClsById(this.editForm.stuBraId)
        this.getStuById(id)
        this.timeVule = 3
        clearInterval(this.timer)
      } else {
        this.timeVule = 0
        return this.$message.error('点击太快了!请休息一下')
      }
    },
    editDialogClosed() {
      this.$refs.editRef.resetFields()
      this.editForm.pubCurs = []
      this.editForm.priCurs = []
      this.timeVule = 0
      this.timer = setInterval(() => {
        this.timeVule++
      }, 1000)
    },
    async getStuById(id) {
      const { data: res } = await this.$http.get('stu/one/' + id)
      if (res.code !== 20000) {
        return this.$message.error('查询出错啦~')
      }
      this.editForm = res.data
      this.editDialogVisible = true
    },
    editSub() {
      this.$refs.editRef.validate(async valid => {
        if (!valid) return
        this.editForm.updateBy = window.sessionStorage.getItem('rootname')
        const { data: res } = await this.$http.put('stu/update', this.editForm)
        if (res.code !== 20000) {
          return this.$message.error('更新失败!')
        }
        this.editDialogVisible = false
        this.getStuList()
        return this.$message.success('更新成功!')
      })
    },
    handleClose(item) {
      this.editForm.priCurs.splice(this.editForm.priCurs.indexOf(item), 1)
    },
    delDialog(id) {
      this.delDialogVisible = true
      this.delStuId = id
    },
    async delStuById() {
      const { data: res } = await this.$http.delete('stu/del/' + this.delStuId)
      if (res.code !== 20000) {
        return this.$message.error('删除失败!')
      }
      this.delDialogVisible = false
      this.getStuList()
      return this.$message.success('删除成功!')
    }
  },
  mounted() {
    this.getAllDept()
  },
  beforeDestroy() {
    clearInterval(this.timer)
  }
}
</script>

<style lang="less" scoped>
.el-col {
  line-height: 40px;
}

.el-row {
  margin-bottom: 10px;
  text-align: left;
}

.el-form-item {
  text-align: left;
}
.el-tag + .el-tag {
  margin-left: 10px;
}
</style>
